import com.sun.corba.se.impl.orbutil.ObjectUtility;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-04-05
 * Time: 11:16
 */
public class TCPEchoServer {
    private ServerSocket serverSocket = null;

    public TCPEchoServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public String process(String request) {
        return request;
    }

    public void processConnect(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线\n", clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            //这个对象将自动读取【字节流/其他流】为【字符流】
            PrintWriter printWriter = new PrintWriter(outputStream);
            //这个对象将自动写入【字符流】化为【字节流/其他流】
            while(scanner.hasNext()) {//死循环了，除非客户端关闭~
                String request = scanner.next();//nextLine有坑很烦
                String response = process(request);
                printWriter.println(response);//换行记得加~
                printWriter.flush();
                System.out.printf("[%s : %d] 发来请求：%s, 将对其返回响应：%s\n", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);
            }
            System.out.printf("[%s:%d] 客户端下线\n", clientSocket.getInetAddress().toString(),
                    clientSocket.getPort());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        while(true) {
            Socket clientSocket = serverSocket.accept();
            executorService.submit(() -> {
                try {
                    processConnect(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer tcpEchoServer = new TCPEchoServer(9090);
        tcpEchoServer.start();
    }
}
